import { createRouter, createWebHashHistory } from 'vue-router'
import { getToken } from '@/utils/auth' // get token from cookie
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import microApp from '@micro-zoe/micro-app'

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

import { constantRoutes, dynamicRoutes, constantTailRoutes } from './routes'

export const wholeRoutes = constantRoutes.concat(dynamicRoutes);



const router = createRouter({
  history: createWebHashHistory(),
  /**
   * 说明：
   * 1、notFoundAndNoPower 默认添加 404、401 界面，防止一直提示 No match found for location with path 'xxx'
   * 2、backEnd.ts(后端控制路由)、frontEnd.ts(前端控制路由) 中也需要加 notFoundAndNoPower 404、401 界面。
   *    防止 404、401 不在 layout 布局中，不设置的话，404、401 界面将全屏显示
   */
  routes: constantRoutes.concat(constantTailRoutes),
})


router.beforeEach((to, from) => {
  // start progress bar
  NProgress.start()
  if (to.matched.length == 0) {
    if (from.path === '/welcome') {
      return { path: '/404' }
    } else {
      return { path: '/welcome', query: { redirect: to.path } }
    }
  } else {
    // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        return { path: '/' }
      } else if(from.path == '/' && '/' == to.path){
        return '/welcome'
      }
    } else {
      /* has no token*/
      if (whiteList.indexOf(to.path) == -1) {
        // other pages that do not have permission to access are redirected to the login page.
        return `/login?redirect=${to.path}`
      }
    }
  }
})



router.afterEach(() => {
  NProgress.done()
})


// 注册主应用路由
microApp.router.setBaseAppRouter(router)

export default router
